package scau.hotel.hotel_sys.service.Impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import scau.hotel.hotel_model.redis.RedisCache;
import scau.hotel.hotel_sys.entity.SysUser;
import scau.hotel.hotel_sys.mapper.SysUserRoleMapper;
import scau.hotel.hotel_sys.security.domain.LoginUser;
import scau.hotel.hotel_sys.security.service.TokenService;
import scau.hotel.hotel_sys.security.utils.SecurityUtils;
import scau.hotel.hotel_sys.service.IAuthenticationService;
import scau.hotel.hotel_sys.service.ISysUserService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AuthenticationServiceImpl implements IAuthenticationService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    ISysUserService iSysUserService;

    @Resource
    private TokenService tokenService;

    @Resource
    private RedisCache redisCache;

    @Override
    public String login(String username, String password) throws AuthenticationException {
        if (this.iSysUserService.queryByUsername(username) == null) {
            throw new UsernameNotFoundException("找不到该用户");
        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // redis中存储loginUser，为简化暂时使用username为key
        // 最终笔记项目使用了uuid生成唯一key，效果相同
        String userKey = loginUser.getUsername();

        // redis中存储loginUser
        loginUser.setLoginTime(System.currentTimeMillis());
        int expireTime = 30 * 60 * 1000; //设置loginUser的缓存过期时间为30分钟。建议与token过期时间相等或者小于token过期时间。
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime);

        // 调用工具类存储login对象
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);

        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 获得登录用户信息
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Map<String, Object> getUserInfo() throws AuthenticationException {
        HashMap<String,Object> userInfo = new HashMap<>();
        // 注意以下这句需要在LoginUser类中添加SysUser属性
        // 在UserDetailsServiceImpl创建LoginUser对象时，将sysUser设置进去。
        // 比较简单，此处就不贴出LoginUser代码和UserDetailsServiceImpl代码
        // 目的是：方便通过loginUser直接拿到sysUser。这样有利于笔记3实现权限。
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        userInfo.put("roles",sysUser.getRoles());
        userInfo.put("name",sysUser.getUsername());
        userInfo.put("avatar",sysUser.getAvatar());
        return userInfo;
    }
}
